package com.hero.herocat;

import com.hero.herocat.handler.IHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;

import java.util.Iterator;
import java.util.List;

/**
 * @author linhui
 */
public class ServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private List<IHandler> handlers;

    public ServerHandler(List<IHandler> handlers) {
        this.handlers = handlers;
    }



    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) throws Exception {
        HttpCustomRequest req = new HttpCustomRequest(fullHttpRequest);
        HttpServletResponse res = new HttpServletResponse(fullHttpRequest, channelHandlerContext);



        /// 交给handler处理
        Iterator<IHandler> iterator = handlers.iterator();
        while (iterator.hasNext()) {
            IHandler handler = iterator.next();
            if (handler.needHandle(req.getPathName())) {
                handler.handle(req, res);
                break;
            }
        }
    }
}
